package com.ruoyi.framework.web.service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.ruoyi.common.enums.UserType;
import com.ruoyi.system.domain.GwOperationAccount;
import com.ruoyi.system.domain.GwOperationAccountRole;
import com.ruoyi.system.domain.GwPlatformAccountRole;
import com.ruoyi.system.domain.GwPlatformRole;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IGwOperationRoleService;
import com.ruoyi.system.service.IGwPlatformRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysRoleService;

import javax.annotation.Resource;

/**
 * 用户权限处理
 * 
 * @author ruoyi
 */
@Component
public class SysPermissionService
{
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysMenuService menuService;
    @Resource
    private GwOperationAccountRoleMapper accountRoleMapper;
    @Resource
    private GwOperationRoleMenuMapper operationRoleMenuMapper;
    @Resource
    private GwOperationAccountMapper operationAccountMapper;
    @Resource
    private GwPlatformAccountRoleMapper platformAccountRoleMapper;
    @Resource
    private GwPlatformRoleMenuAppletMapper platformRoleMenuAppletMapper;
    @Resource
    private GwPlatformRoleMenuPcMapper platformRoleMenuPcMapper;
    @Resource
    private IGwPlatformRoleService platformRoleService;
    @Resource
    private IGwOperationRoleService operationRoleService;

    private static final String AGENT_ROLE_KEY = "agent_role";
    private static final String ENTERPRISE_SYSTEM_ROLE_KEY = "enterprise_system_role";

    private static final String ENTERPRISE_ADMIN_APPLET_ROLE_KEY = "enterprise_admin_applet_role";

    /**
     * 获取角色数据权限
     * 
     * @param user 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(SysUser user)
    {
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin())
        {
            roles.add("admin");
        }
        else
        {
            roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));

            if(user.getUserType().equals(UserType.SYSTEM_USER.getCode()) || user.getUserType().equals(UserType.ENTERPRISE_USER.getCode()) || user.getUserType().equals(UserType.AGENT_USER.getCode())){
                roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
            }
            if(user.getUserType().equals(UserType.PLATFORM_USER.getCode())){
                roles.addAll(platformRoleService.selectRolePermissionByUserId(user.getUserId()));
            }
            if(user.getUserType().equals(UserType.OPERATION_USER.getCode())){
                roles.addAll(operationRoleService.selectRolePermissionByUserId(user.getUserId()));
            }
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     * 
     * @param user 用户信息
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(SysUser user)
    {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin())
        {
            perms.add("*:*:*");
        }
        else
        {
            if(user.getUserType().equals(UserType.SYSTEM_USER.getCode())){
                perms.addAll(getSystemMenu(user));
            }
            if(user.getUserType().equals(UserType.ENTERPRISE_USER.getCode())){
                //直接取系统中企业管理员角色
                Set<String> rolePerms = menuService.selectMenuPermsByRoleKey(ENTERPRISE_SYSTEM_ROLE_KEY);
                perms.addAll(rolePerms);
            }
            if(user.getUserType().equals(UserType.PLATFORM_USER.getCode())){
                Set<String> rolePerms = getPlatformAccountPcMenu(user);
                perms.addAll(rolePerms);
            }
            if(user.getUserType().equals(UserType.OPERATION_USER.getCode())){
                Set<String> rolePerms = getOperationAccountMenu(user);
                perms.addAll(rolePerms);
            }
            if(user.getUserType().equals(UserType.AGENT_USER.getCode())){
                //直接取系统中代理商角色
                Set<String> rolePerms = menuService.selectMenuPermsByRoleKey(AGENT_ROLE_KEY);
                perms.addAll(rolePerms);
            }
        }
        return perms;
    }

    /**
     * 获取小程序菜单数据权限
     *
     * @param user 用户信息
     * @return 菜单权限信息
     */
    public Set<String> getAppletMenuPermission(SysUser user)
    {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin())
        {
            perms.add("*:*:*");
        }
        else
        {
            if(user.getUserType().equals(UserType.ENTERPRISE_USER.getCode())){
                //获取小程序的所有菜单权限
                Set<String> rolePerms = menuService.selectMenuPermsByRoleKey(ENTERPRISE_ADMIN_APPLET_ROLE_KEY);
                perms.addAll(rolePerms);
            }
            if(user.getUserType().equals(UserType.PLATFORM_USER.getCode())){
                Set<String> rolePerms = getPlatformAccountAppletMenu(user);
                perms.addAll(rolePerms);
            }
        }
        return perms;
    }

    private Set<String> getSystemMenu(SysUser user){
        Set<String> perms = new HashSet<String>();
        List<SysRole> roles = user.getRoles();
        if (!CollectionUtils.isEmpty(roles))
        {
            for (SysRole role : roles)
            {
                if (StringUtils.equals(role.getStatus(), UserConstants.ROLE_NORMAL) && !role.isAdmin())
                {
                    Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                    role.setPermissions(rolePerms);
                    perms.addAll(rolePerms);
                }
            }
        }
        else
        {
            perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
        }
        return perms;
    }

    private Set<String> getOperationAccountMenu(SysUser user){
        Set<String> perms = new HashSet<String>();
        if(user==null || StringUtils.isEmpty(user.getChannelId())){
            return perms;
        }
        //根据userId查询角色
        GwOperationAccountRole accountRole = new GwOperationAccountRole();
        accountRole.setAccountId(user.getChannelId());
        List<GwOperationAccountRole> accountRoleList = accountRoleMapper.selectGwOperationAccountRoleList(accountRole);
        if(!CollectionUtils.isEmpty(accountRoleList)){
            for(GwOperationAccountRole vo:accountRoleList){
                List<String> rolePerms = operationRoleMenuMapper.selectMenuByAccountRoleId(vo.getOperationRoleId());
                for (String perm : rolePerms)
                {
                    if (StringUtils.isNotEmpty(perm))
                    {
                        perms.addAll(Arrays.asList(perm.trim().split(",")));
                    }
                }
            }
        }
        return perms;
    }

    private Set<String> getPlatformAccountAppletMenu(SysUser user){
        Set<String> perms = new HashSet<String>();
        if(user==null || StringUtils.isEmpty(user.getChannelId())){
            return perms;
        }
        //根据userId查询角色
        GwPlatformAccountRole accountRole = new GwPlatformAccountRole();
        accountRole.setAccountId(user.getChannelId());
        List<GwPlatformAccountRole> accountRoleList = platformAccountRoleMapper.selectGwPlatformAccountRoleList(accountRole);
        if(!CollectionUtils.isEmpty(accountRoleList)){
            for(GwPlatformAccountRole vo:accountRoleList){
                List<String> rolePerms = platformRoleMenuAppletMapper.selectMenuByAccountRoleId(vo.getPlatformRoleId());
                for (String perm : rolePerms)
                {
                    if (StringUtils.isNotEmpty(perm))
                    {
                        perms.addAll(Arrays.asList(perm.trim().split(",")));
                    }
                }
            }
        }
        return perms;
    }

    private Set<String> getPlatformAccountPcMenu(SysUser user){
        Set<String> perms = new HashSet<String>();
        if(user==null || StringUtils.isEmpty(user.getChannelId())){
            return perms;
        }
        //根据userId查询角色
        GwPlatformAccountRole accountRole = new GwPlatformAccountRole();
        accountRole.setAccountId(user.getChannelId());
        List<GwPlatformAccountRole> accountRoleList = platformAccountRoleMapper.selectGwPlatformAccountRoleList(accountRole);
        if(!CollectionUtils.isEmpty(accountRoleList)){
            for(GwPlatformAccountRole vo:accountRoleList){
                List<String> rolePerms = platformRoleMenuPcMapper.selectMenuByAccountRoleId(vo.getPlatformRoleId());
                for (String perm : rolePerms)
                {
                    if (StringUtils.isNotEmpty(perm))
                    {
                        perms.addAll(Arrays.asList(perm.trim().split(",")));
                    }
                }
            }
        }
        return perms;
    }
}
